<template>
  <Headers page="search" />
  <div class="content">
    <el-card style="margin: 10px">
      <el-input
        v-model="keyword"
        size="large"
        placeholder="请输入消费码、联系电话、车牌号码"
        class="mpt10"
        style="width: 70%; margin-right: 10px"
      >
        <template #append>
          <el-button :icon="Camera" @click="recognizeCar" />
        </template>
      </el-input>
      <el-button type="primary" @click="search"> 查询 </el-button>
    </el-card>
    <el-card v-for="item in orders" :key="item.id" style="margin: 10px">
      <el-row style="height: 40px">
        <el-col :span="14">订单号：{{ item.ordersn }}</el-col>
        <el-col :span="4"
          ><el-button type="success" @click="setScenePay(item)" v-if="item.status!=1 && item.status!=3 && item.status!=4">
            补差价
          </el-button></el-col
        >
        <el-col :span="6"
          >
          <el-popconfirm title="确认要退款吗？" @confirm="onRefundOrder(item.ordersn)" v-if=" item.status==2 && item.suit[0].paysource!='微信'">
            <template #reference>
              <el-button   
              v-if="item.salemanid==userStore.userId"         
                type="warning"               
              >
                退款
          </el-button>
            </template>
          </el-popconfirm>
          <el-button type="primary" @click="onPrint(item)" v-print="print" v-if="item.status!=1 && item.status!=3 && item.status!=4">
            打印
          </el-button>
         
          </el-col
        >
      </el-row>
      <el-row>
        <el-col :span="12">线路：{{ item.suit[0].productname }}</el-col>
        <el-col :span="12">车型：{{ item.suit[0].suit_name }}</el-col>
      </el-row>
      <el-row>
        <el-col :span="14"
          >航班：{{ item.suit[0].usedate }}({{ item.suit[0].flight }})</el-col
        >
        <el-col :span="10" v-if="item.suit[0].drivernum == '1'"
          ><div style="color: red">含跟车司机</div></el-col
        >
      </el-row>
      <el-row>
        <el-col :span="12">姓名：{{ item.suit[0].linkman }}</el-col>
        <el-col :span="12">电话：{{ item.suit[0].linktel }}</el-col>
      </el-row>
      <el-row>
        <el-col :span="24">证件：{{ item.suit[0].linkidcard }}</el-col>
      </el-row>
      <el-row>
        <el-col :span="24">长度：{{ item.suit[0].car[0].size }}</el-col>
      </el-row>
      <el-row>
        <el-col :span="12">车型：{{ item.suit[0].car[0].cartype }} {{ item.suit[0].remark?'('+item.suit[0].remark+')':'' }}</el-col>
        <el-col :span="12">车牌：{{ item.suit[0].car[0].carnumber }}</el-col>
      </el-row>
     
      <el-row>
        <el-col :span="12">车辆价格：{{ item.suit[0].price }}</el-col>
        <el-col :span="12" v-if="item.suit[0].drivernum == '1'"
          >司机价格：{{ item.suit[0].driverprice }}</el-col
        >
      </el-row>
      <el-row>
        <el-col :span="12">补差价：{{ item.scenepay }}</el-col>
        <el-col :span="12" style="color:red">总金额：{{ (Number(item.price) + Number(item.scenepay)).toFixed(2) }}</el-col>
      </el-row>
      <el-row>
        <el-col :span="12" v-if="item.suit[0].status == '1'"
          >订单状态：待支付</el-col
        >
        <el-col :span="12" v-if="item.suit[0].status == '2'"
          >订单状态：已支付</el-col
        >
        <el-col :span="12" v-if="item.suit[0].status == '3'"
          >订单状态：已关闭</el-col
        >
        <el-col :span="12" v-if="item.suit[0].status == '4'"
          >订单状态：已退款</el-col
        >
        <el-col :span="12" v-if="item.suit[0].status == '5'"
          >订单状态：已核销</el-col
        >
        <el-col :span="12">支付方式：{{ item.suit[0].paysource }}</el-col>
      </el-row>
      <el-row v-if="item.finishtime">
        <el-col :span="12" 
          >核销时间：{{ item.finishtime }} </el-col
        >   
        <el-col :span="12"
          >核销员：{{ item.verify_admin }}</el-col
        >    
      </el-row>
      <el-row v-if="item.suit[0].saleman">       
        <el-col :span="12" 
          >销售员：{{ item.suit[0].saleman }}</el-col
        >    
      </el-row>
    </el-card>
  </div>
  <div id="printContent" v-if="printData">
    <div class="box">
      <div class="printBox">
        <div>
          <div>订单编号：{{ printData.ordersn }}</div>
          <div>路　　线：{{ printData.productname }}</div>
          <div>票　　类：{{ printData.suit[0].suit_name }}</div>
          <div>
            使用日期：{{ printData.suit[0].usedate }}({{
              printData.suit[0].flight
            }})
          </div>
          <div>姓　　名：{{ printData.suit[0].linkman }}</div>
          <div>电　　话：{{ printData.suit[0].linktel }}</div>
          <div>车牌号码：{{ printData.suit[0].car[0].carnumber }}</div>
          <div>车辆票价：{{ (parseFloat(printData.suit[0].price)+parseFloat(printData.scenepay)).toFixed(2) }}</div>
          <div v-if="printData.suit[0].drivernum == '1'">
            司机票价：{{ printData.suit[0].driverprice }}
          </div>
          <div v-if="printData.suit[0].merchant_member_id!='0'">
            操　　作：月结支付{{ printData.scene[0]?'-'+ printData.scene[0].saleman:'' }}
          </div>
          <div v-else>操　　作：{{ printData.suit[0].saleman?printData.suit[0].saleman:'线上自助下单' }}{{ printData.scene[0]?'-'+ printData.scene[0].saleman:'' }}</div>
          <div>{{ printData.addtime }}</div>
        </div>
        <div class="qrcode">
          <div v-if="printData.suit[0].drivernum == '1'">含司机</div>
          <VueQrcode
            :value="'https://www.chuandaolundu.com/h5/#/subPackages/verify/order?eticketno=' +printData.suit[0].eticketno"
            :color="{}"
            :width="100"
            type="image/png"
          />
          <div>凭此二维码核销</div>
          <div>{{ printData.suit[0].car[0].cartype }} {{ printData.suit[0].remark?'('+printData.suit[0].remark+')':'' }}</div>
          <div>{{ printData.suit[0].paysource }}</div>
        </div>
      </div>
    </div>
  </div>
  <el-dialog v-model="payDialog" title="补差价" :close-on-click-modal="false">
    <el-input v-model="form.fee" size="large" input-style="color:red;font-size:40px;height:50px" @input="form.fee= form.fee.replace(/[^\d|\.]/g, '')">
      <template #prefix>
        <span>￥</span>
      </template>
    </el-input>
    <el-card class="mpt10" v-if="curprice!=form.fee">
      <template #header>备注</template>
      <el-card header="可选备注" class="mpb10" style="display: flex;flex-direction: column;justify-content:space-between;" v-if="curprice!=form.customPrice">
        <el-button v-for="item in remarks" style="margin-left: 10px;margin-bottom: 10px;" @click="changeRemark(item)">{{ item }}</el-button>
      </el-card>      
      <el-input v-model="form.remark" size="large" />
      
    </el-card>
    <el-card class="mpt10">
      <template #header> 计算规则 </template>
      <el-radio-group v-model="computerType" @change="selectComputerType" class="mpt10">
        <el-radio 
          :value="1"
          size="large"
          border
          class="mpb10"        
        >
          <div>长度</div>         
        </el-radio>
        <el-radio 
          :value="2"
          size="large"
          border
          class="mpb10"        
        >
          <div>重量</div>         
        </el-radio>
       
      </el-radio-group>   
    </el-card>
    <el-card class="mpt10">
      <template #header>支付方式</template>
      <el-radio-group v-model="form.paysource">
        <el-radio value="scan" size="large" border class="mpb10" v-if="currOrder.suit[0].merchant_id=='0'">扫码支付</el-radio> 
        <el-radio value="cash" size="large" border class="mpb10" v-if="currOrder.suit[0].merchant_id=='0'">现金支付</el-radio>    
        <el-radio value="monthlysettle" size="large" border class="mpb10" v-if="currOrder.suit[0].merchant_id!='0'">月结支付</el-radio>           
      </el-radio-group>
    </el-card>
    <el-card class="mpt10">
      <template #header
        >车辆信息（行驶证识别）

        <el-button-group class="ml-4 fr">
          <el-button :icon="Camera" @click="supplementCar" />
        </el-button-group>
      </template>
      <el-input
        v-model="form.carnum"
        size="large"
        placeholder="请输入车牌号码"
      />
      <el-input
        v-model="form.cartype"
        size="large"
        placeholder="请输入车型"
        class="mpt10"
      />
      <view style="display: flex;flex-direction: row;justify-content: space-between;">
        <el-input
        v-model="changdu"
        size="large"
        placeholder="长度"
        class="mpt10"
        @input="changeCarSize"
        style="width:150px;"
      />
      <view class="mpt10" style="line-height:40px">X</view>
      <el-input
        v-model="kuandu"
        size="large"        
        class="mpt10"
        placeholder="宽度"
        @input="changeCarSize"
        style="width:150px;"
      />
      <view class="mpt10" style="line-height:40px">X</view>
      <el-input
        v-model="gaodu"
        size="large"      
        class="mpt10"
        placeholder="高度"
        @input="changeCarSize"
        style="width:150px;"
      />
      <view class="mpt10" style="line-height:40px">mm</view>
      </view>
      <el-input
        v-if="computerType==2"
        v-model="form.weight"
        size="large"
        placeholder="请输入车辆重量（吨）"
        class="mpt10"
        @input="changeCarSize"
      />
    </el-card>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="payDialog = false">取消</el-button>
        <el-button type="primary" @click="submitScenePay"> 提交 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import Headers from "@/components/Header.vue";
import { onMounted, ref, reactive, onUnmounted } from "vue";
import { useUser } from "@/stores/user";
import request from "@/utils/request";
import VueQrcode from "vue-qrcode";
import { Camera } from "@element-plus/icons-vue";
import { getcar, creatWS, getUploadData, closeCap } from "@/utils/gpy";
import { ElMessageBox } from "element-plus";
onMounted(() => {
  creatWS();
});
onUnmounted(() => {
  closeCap();
});
const userStore = useUser();
const ws = ref(null);
const keyword = ref("");
const printData = ref();
const daterange = ref([]);
const computerType = ref(1)
const orders = ref([]);
const stock_rule = ref([])
const price_rule = ref([])
const weight_price_rule=ref([])
const size_price_rule=ref([])
const deduct_stock_type = ref('')
const deduct_price_type = ref('')
const curprice = ref(0)
const print = reactive({
  id: "printContent",
});
const remark = ref('')
const changeRemark = (e)=>{
  form.remark = e
}
const remarks = ref([])

const payDialog = ref(false);
const currOrder=ref()
const form = reactive({
  fee: 0,
  ordersn: "",
  carnum:'',
  cartype:'',
  size:'',
  paysource:'',
  remark:"",
  weight:''
});

const changdu=ref("")
const kuandu=ref("")
const gaodu=ref("")

const selectComputerType = async (value) => {
  if(value==1){
    price_rule.value=size_price_rule.value
  }else{
    price_rule.value=weight_price_rule.value
  }
  getPriceRule(currOrder.value)
  changeCarSize()
};
const setScenePay = (order) => {
  payDialog.value = true;
  form.ordersn = order.ordersn;
  form.fee=0
  form.carnum = order.suit[0].car[0].carnumber;
  form.cartype = order.suit[0].car[0].cartype;
  form.size = order.suit[0].car[0].size;
  form.paysource=''
  form.remark=''  
  form.weight=0
  computerType.value=1
  let rex = new RegExp(/\d+/g)         
  changdu.value = form.size.match(rex)[0]
  kuandu.value = form.size.match(rex)[1]
  gaodu.value = form.size.match(rex)[2]
  getPriceRule(order)
  getRemarks()
};
const submitScenePay = async () => {
  if (!form.fee || !form.ordersn) {
    ElMessageBox.alert("输入金额不正确");
    return
  }
  if(!form.paysource){
    ElMessageBox.alert("请选择支付方式");
    return
  }
  let params = {
    url: "/scene/order/scenepay",
    method: "POST",
    data: {
      ordersn: form.ordersn,
      total_fee: form.fee,
      carnum:form.carnum,
      cartype:form.cartype,
      size:form.size,
      paysource:form.paysource,
      saleman: userStore.userName,
      salemanid: userStore.userId,
      remark:form.remark
    },
  };
  let res = await request(params);
  if (res.status) {
    ElMessageBox.alert("操作成功");
  }
  payDialog.value = false;
  search();
};


const search = async () => {
  orders.value = [];
  let params = {
    url: "/scene/order/search",
    method: "POST",
    data: {
      keyword: keyword.value.replace(/^\s+|\s+$/g, ""),
    },
  };
  let res = await request(params);
  if (res.status) {
    if (res.data.total > 0) {
      orders.value = res.data.list;
    } else {
      ElMessageBox.alert("订单不存在");
    }
  }
};

const changeCarSize = ()=>{
  
    let order = currOrder.value
    let rex = new RegExp(/\d+/)
    if(changdu.value){
      form.size=changdu.value;
    }
    if(kuandu.value){
      form.size+='X'+kuandu.value;
    }
    if(gaodu.value){
      form.size+='X'+gaodu.value;
    }    
    let size = computerType.value==1?form.size.match(rex)[0] :form.weight    
    let price = order.price    
    if(deduct_price_type.value){
      price_rule.value.forEach(e=>{
        if(e.price>0 && e.max>0){        
          if(Number(size)>=Number(e.min) && Number(size)<=Number(e.max)){          
            

            if(computerType.value==1){
              form.fee = (( Math.round(size/1000 * 10)/10) * e.price)-price
              curprice.value = (( Math.round(size/1000 * 10)/10) * e.price)-price
            }else{
              form.fee = (size * e.price)-price
              curprice.value = (size * e.price)-price
            }   
          }
        }
      })
    }
}

const getPriceRule = async (order) => {   
  currOrder.value = order
  let params = {
    url: "/scene/ferry/book_suit",
    method: "POST",
    data: {
      ferry_id: order.suit[0].productaid,
      suit_id: order.suit[0].suitid,
      date: order.usedate,
    },
  };
  let res = await request(params);
  if (res.status) {    
    size_price_rule.value=res.data.prices[0].size_price_rule
    weight_price_rule.value=res.data.prices[0].weight_price_rule
    if(computerType.value==1){
      price_rule.value=size_price_rule.value
    }else{
      price_rule.value=weight_price_rule.value
    }
    deduct_price_type.value = res.data.prices[0].deduct_price_type      
    changeCarSize()
  }
};

const getRemarks = async () => {     
  let params = {
    url: "/scene/ferry/get_remark",
    method: "POST",
    data: {
     
    },
  };
  let res = await request(params);
  if (res.status) {    
    remarks.value=res.data   
  }
};

const recognizeCar = async () => {
  getcar();
  let intervalId = setInterval(() => {
    let data = getUploadData();    
    if (data != "") {
      let arr = data.split("|");
      if (arr.length > 1) {
        let data2 = arr[1].substring(0, arr[0]);
        data2 = JSON.parse(data2);
        if (data2.face) {
          keyword.value = data2.face.licensePlateNumber;
        }
      } else {
        ElMessageBox.alert("识别失败，请检查是否放好证件或光线不足", "错误");
        keyword.value = "";
      }
      clearInterval(intervalId);
    }
  }, 500);
};

const supplementCar = async () => {
  getcar();
  let intervalId = setInterval(() => {
    let data = getUploadData();
    if (data != "") {
      let arr = data.split("|");
      if (arr.length > 1) {
        let data2 = arr[1].substring(0, arr[0]);
        data2 = JSON.parse(data2);
        if (data2.face) {
          form.carnum = data2.face.licensePlateNumber;
          form.cartype = data2.face.vehicleType;         
        }
        if (data2.back) {
          form.size = data2.back.overallDimension;
          let rex = new RegExp(/\d+/g)         
          changdu.value = form.size.match(rex)[0]
          kuandu.value = form.size.match(rex)[1]
          gaodu.value = form.size.match(rex)[2]
          changeCarSize()
        }
      } else {
        ElMessageBox.alert("识别失败，请检查是否放好证件或光线不足", "错误");
        form.carnum = "";
        form.cartype = "";
        form.size = "";
      }
      clearInterval(intervalId);
    }
  }, 500);
};

const onPrint = (data) => {
  printData.value = data;
};

const onRefundOrder = async (ordersn)=>{
  let params = {
    url: "/scene/order/refund_order",
    method: "POST",
    data: {
      ordersn:ordersn
    }
  };
  let res = await request(params);
  if(res.status){
    ElMessageBox.alert("退款成功");
  }else{
    ElMessageBox.alert("退款失败");
  }  
  search()
}
</script>

<style scoped>
.content {
  margin: 20px auto;
  max-width: 600px;

  display: flex;
  flex-direction: column;
  justify-content: center;
}
#printContent {
  display: none;
}
.mpt10 {
  margin-top: 10px;
}
.mpb10 {
  margin-bottom: 10px;
}
@media print {
  @page {
    size: auto; /* auto is the initial value */
    margin: 0 0;
  }

  #printContent {
    display: flex;
  }
  .box {
    width: 100%;
    display: flex;
    justify-content: center;
  }
  .printBox {
    width: 95%;
    display: flex;
    flex-direction: row;
    margin-top: 5px;
    transform: rotate(180deg);
    font-size: 12px;
    position: relative;
  }
  .printBox div {
    line-height: 20px;
  }
  .qrcode {
    position: absolute;
    margin: 20px 0 0 0px;
    text-align: center;
    right: 0px;
  }
}
.el-row {
  height: 26px;
}
</style>